// pages/payment/payment.js
import {
  getbaseUrl,
  requestUtil
} from "../../utils/request"

const io  = require('../../utils/weapp.socket.io')

let news = null
Page({

  /**
   * 页面的初始数据
   */
  data: {
    show: false,
    time: '12:01',
    baseUrl: '',
    // 店铺的id
    storeId: 1,
    // 店铺的地址
    storeAddress: '',
    // 店铺的名字
    storeName: '',
    // 店铺的距离
    storeDistance: "",
    openId: "",
    // 订单编号
    orderNo: "",
    isYao: "收起更多",

    // 用户的金额
    money: 0,
    // 优惠券
    disRmb: 0,
    haveDiscountDate: [],
    disId: 0,
    userId:0,
    // 用户的密码
    isPayPassword: 0,

    shop: {
      orderList: [],
      shopNum: 0,
      totalPrice: 0,
      showData: [],
      shopLength: 0,

    },
    // passError:"密码错误请重试"
    passError: "",
    showPass: false,
    warnning: "为了您的资金安全，请初始密码",
    submitPassword: 0,
    plase: "",
  },

  bindTimeChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      time: e.detail.value,
      totalPirce: 0
    })
  },

  // 获取购物车数据
  orderlist() {
    let storeId = this.data.storeId
    let openId = this.data.openId
    let res = requestUtil({
      url: "/shop/getCartList",
      methed: "get",
      data: {
        storeId,
        openId
      }
    })
    res.then(({
      data
    }) => {
      if (data.status == 200) {
        this.orderData(data.data)
        // console.log(data.data)
        // wx.showToast({
        //   title: '获取数据成功',
        //   icon:"error"
        // })
      } else {
        wx.showToast({
          title: '获取数据失败',
        })
      }
    })
  },

  // 获取数据进行遍历和过滤
  orderData(data) {

    this.setData({
      "shop.orderList": data,
      "shop.shopLength": data.length
    })
    this.calculate(data)
    this.changeHeight()

  },

  //对数据进行计算

  calculate(data) {
    // 商品总价
    let totalPrice = data.reduce((total, item) => {
      return total += item.price * item.num
    }, 0)
    //商品数量
    let num = data.length

    this.setData({
      "shop.totalPrice": totalPrice.toFixed(2),
      "shop.shopNum": num,
      // 获取基本域名
      baseUrl: getbaseUrl() + "/image/"
    })
    // console.log(this.data.baseUrl)
  },

  //控制显示高度
  changeHeight() {
    let a = this.data.isYao == "展开全部" ? "收起更多" : '展开全部';
    this.setData({
      isYao: a
    })
    setTimeout(() => {
      // console.log( this.data.shop.orderList,"fesfes")
      if (this.data.isYao == "展开全部") {
        // console.log(this.data.shop.orderList.slice(0, 2))
        // this.data.shop.orderList= this.data.shop.orderList.splice(0,2)
        this.setData({
          "shop.showData": this.data.shop.orderList.slice(0, 2),
        })
        // console.log(this.data.isYao)
        return
      }

      if (this.data.isYao == "收起更多") {
        // console.log(this.data.shop.orderList.slice(0, this.data.shop.orderList.length))
        // this.data.shop.orderList= this.data.shop.orderList.splice(0,2)
        this.setData({
          "shop.showData": this.data.shop.orderList.slice(0, this.data.shop.orderList.length),
        })
        // console.log(this.data.isYao)
        return
      }
    }, 100)
  },

  // 日期转化
  dateConversion(value) {
    var d = new Date(value);
    var date =
      d.getFullYear() +
      "-" +
      (d.getMonth() + 1) +
      "-" +
      d.getDate() +
      " " +
      d.getHours() +
      ":" +
      d.getMinutes() +
      ":" +
      d.getSeconds();
    return date;
  },


  // 获取用户的金额
  getUserMoney() {
    // console.log("执行第一次")
    let openId = this.data.openId
    let res = requestUtil({
      url: "/shop/getUserMoney",
      method: "get",
      data: {
        openId
      }
    })
    res.then(({
      data
    }) => {
      // console.log(data)
      let totalPrice = data.data.reduce((total, item) => {
        return total += item.money
      }, 0)
      if (data.status == 200) {
        this.setData({
          money: totalPrice
        })
      } else {
        this.setData({
          money: 0
        })
      }
    })
  },

  // 取消支付
  cancelPay() {

    let disId = this.data.disId
    this.clear()
    this.putOrder(0, disId)
    this.toShopDetail()
  },

  // 狗扣钱
  deduction(openId, money) {
    let disRmb = this.data.disRmb
    requestUtil({
      url: "/shop/noMatchPassword",
      method: "get",
      data: {
        openId,
        money: -(money - disRmb)
      }
    })
  },

  // 获取用户的密码
  getUserPayPassword() {
    let openId = this.data.openId

    let res = requestUtil({
      url: "/shop/getUerPayPassword",
      method: "get",
      data: {
        openId
      }
    })

    res.then(({
      data
    }) => {
      // console.log(data)
      if (data.status == 200) {
        // console.log(data.data)
        this.setData({
          isPayPassword: data.data.state
        })
      } else {
        this.setData({
          isPayPassword: data.data
        })
      }
    })

  },

  // 支付确认回调
  submit(e) {
    let totalPrice = this.data.shop.totalPrice
    let money = this.data.money
    // console.log(totalPrice,money)
    if (totalPrice > money) {
      this.setData({
        passError: "账户余额不足？"
      })
      return
    }

    wx.showLoading({
      title: '数据加载中',
    })
    let password = e.detail.value
    let openId = this.data.openId
    let disId = this.data.disId

    let res = requestUtil({
      url: "/shop/matchPassword",
      method: "get",
      data: {
        password,
        openId
      }
    })
    res.then(({
      data
    }) => {
      // console.log(data)
      // 如果等一就是密码正确
      if (data.data == 1) {
        let p = this.putOrder(1, disId)
        p.then(({
          data
        }) => {
          if (data.status == 200) {
            news.emit("pay",'用户支付了')
            wx.hideLoading()
            this.deduction(openId, totalPrice)
            this.setData({
              show: false
            })
            this.clear()
            wx.switchTab({
              url: '/pages/list/list',
            })
          }
        })
      }

      if (data.data == 0) {
        wx.hideLoading()
        this.setData({
          passError: "密码错误，请重试?"
        })
      }
    })
    // console.log(e.detail.value)
  },

  // 密码的回调
  subPassword(e) {
    let openId = this.data.openId
    let value = e.detail.value
    let submitPassword = this.data.submitPassword
    if (value !== submitPassword) {
      // console.log(e.detail.value)
      this.setData({
        warnning: "请再次输入密码",
        submitPassword: value
      })
    } else {
      // console.log("密码一致")
      let res = requestUtil({
        url: "/shop/insertPaypassword",
        method: "get",
        data: {
          openId,
          password: submitPassword
        }
      })
      res.then(({
        data
      }) => {
        // console.log(data)
        if (data.status == 200) {
          this.setData({
            warnning: "为了您的资金安全，请初始密码",
            showPass: false
          })
          this.getUserPayPassword()
        } else {
          this.setData({
            warnning: "请初始化你的交易密码",
            plase: "密码初始化失败，请再试",
            show: true,
            submitPassword: 0
          })
        }
      })

    }
  },

  //支付订单
  pay() {
    let isPayPassword = this.data.isPayPassword
    if (isPayPassword !== 1) {
      this.setData({
        showPass: true
      })
    } else {
      this.setData({
        show: true
      })
    }

  },
  // 跳转商品详情
  toShopDetail() {
    // console.log(e.currentTarget.dataset)
    // let {orderid,openid,orderno}= e.currentTarget.dataset
    let openId = this.data.openId
    let orderno = this.data.orderNo
    wx.redirectTo({
      url: `/pages/shopDetail/shopDetail?openId=${openId}&orderno=${orderno}`,
    })
  },

  deleteUserDiscount(userId) {
    // console.log(userId)
    let openId = this.data.openId
    let res = requestUtil({
      url: "/shop/deleteUserDiscount",
      method: "get",
      data: {
        userId,
        openId
      }
    })
  },

  // 提交订单

  putOrder(active, disId) {
    // console.log(disId)
      let userId = this.data.userId
    if (disId !== 0) {
      // console.log("我爱你",userId)
      this.deleteUserDiscount(userId)
    }

    let orderNo = parseInt(new Date().getTime() + "1" + Math.ceil(Math.random() * (1000 - 1) + 1))
    if (!orderNo) {
      orderno = parseInt(new Date().getTime() + "1" + Math.ceil(Math.random() * (1000 - 1) + 1))
    }
    let mealCode = parseInt("1" + Math.ceil(Math.random() * (1000 - 1) + 1))
    if (!mealCode) {
      mealCode = parseInt("1" + Math.ceil(Math.random() * (1000 - 1) + 1))
    }
    let openId = this.data.openId
    let orderTime = this.data.time
    let orderDate = this.dateConversion(new Date())
    let storeId = this.data.storeId
    let orderList = this.data.shop.orderList.map(item => {
      item.id = undefined
      return item
    })
    // console.log(orderList)
    let res = requestUtil({
      url: "/shop/pushOrder",
      data: {
        orderList,
        orderTime,
        orderNo,
        active: active,
        openId,
        orderDate,
        storeId,
        mealCode,
        disId

      },
      method: "get"
    })
    this.setData({
      orderNo
    })
    return res
  },

  // 获取用户的优惠券

  getuserDiscount() {
    let openId = this.data.openId
    // console.log(openId)
    let res = requestUtil({
      url: "/shop/getUserAddDiscount",
      method: "get",
      data: {
        openId
      }
    })
    res.then(({
      data
    }) => {
      // console.log(data)
      if (data.status == 200) {
        let totalPrice = this.data.shop.totalPrice
        // 对比数据渲染
        let newArr = data.data.filter(item => {
          return item.isTrue == 1 && item.disRmb < totalPrice
        })
        let newArr1 = data.data.filter(item => {
          return item.disRmb < totalPrice
        })
        // console.log(newArr1,"1")
        // console.log(newArr,"2")
        this.setData({
          disRmb: newArr.length == 0 ? (newArr1.length == 0 ? 0 : newArr1[0].disRmb) : newArr[0].disRmb,
          disId: newArr.length == 0 ? (newArr1.length == 0 ? 0 : newArr1[0].disId) : newArr[0].disId,
          userId: newArr.length == 0 ? (newArr1.length == 0 ? 0 : newArr1[0].userId) : newArr[0].userId,
         
          haveDiscountDate: data.data
        })
      } else {

        this.setData({
          disRmb: 0,
          haveDiscountDate: []
        })
      }
    })
  },

  // 去使用优惠券

  toUserDiscount() {
    // console.log('fesfes')
    let totalPrice = this.data.shop.totalPrice
    wx.navigateTo({
      url: `/pages/useDiscount/useDiscount?totalPrice=${totalPrice}`,
    })
  },

// 创建socket.io通信
    received(){
      let baseUrl = getbaseUrl()
      news = io(baseUrl)
      news.on('connect',(res)=>{
          console.log('connection created.')
      })
    },

  //清除购物车
  clear() {
    let storeId = this.data.storeId
    let openId = this.data.openId
    let res = requestUtil({
      url: '/shop/clearCart',
      data: {
        storeId,
        openId
      },
      method: "get"
    })
    //  res.then(({data})=>{
    //      if(data.status==200){
    //        this.getCartList()
    //          this.onCartClose()
    //      }
    //  })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log("加载")
    if (options) {
      // console.log(options)
      this.setData({
        storeId: options.storeId,
        // 店铺的地址
        storeAddress: options.storeaddress,
        // 店铺的名字
        storeName: options.shopname,
        // 店铺的距离
        storeDistance: options.distance,
        // openId
        openId: options.openId
      })
      // this.getUserMoney()
      this.getUserPayPassword()
    }
    // 获取数据
    this.orderlist()
    this.getuserDiscount()
    //获取高度
    // this.changeHeight()
    // this.received()

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.received()
    if (this.data.haveDiscountDate.length > 0) {
      this.getuserDiscount()
    }
    // console.log(this.data.openId)
    if(this.data.openId){
      // console.log("这是show")
      this.getUserMoney()
      this.setData({
        passError:""
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    news.disconnect()
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    this.setData({
      show: false,
      showPass: false
    })
    news.disconnect()
    console.log("销毁")
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },


  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})